<template>
  <uni-popup-dialog mode="input" title="注销账号"
                    placeholder="请输入内容" @confirm="handle">
    <view v-if="userStore.userInfo.email" class="flex flex-sub flex-direction">
      <view class="flex flex-sub align-center justify-between margin-xs">
        <view class="text-gray ">{{userStore.userInfo.email}}</view>
        <button :disabled="!isSend" class="cu-btn bg-blue  margin-left-xs" @click="getCode">
          {{ isSend ? '验证码' : second }}
        </button>
      </view>
      <view class="margin-xs">
        <uni-easyinput v-model="code" placeholder="请输入验证码"></uni-easyinput>
      </view>
    </view>
    <view v-else>
      您确定要注销？
    </view>
  </uni-popup-dialog>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {isEmail} from "@/utils";
import api from "@/api";
import {useUserStore} from "@/store";

const userStore = useUserStore()
const code = ref('')
const isSend = ref(true)
const second = ref(0)


const getCode = () => {
  isSend.value = false
  second.value = 60
  setInterval(() => {
    second.value--
    if (second.value === 1) {
      isSend.value = true
    }
  }, 1000)
  api.mail.code({
    email: userStore.userInfo.email
  }).then(res => {
    if (res && res.data.code !== 0) {
      isSend.value = true
    }
  })
}

const handle = () => {
  if (userStore.userInfo.email) {
    api.user.destroy({
      email: userStore.userInfo.email,
      code: code.value
    }).then(res => {
      if (res && res.data.code === 0) {
        uni.redirectTo({
          url: '/pages/common/auth/login/login',
          success: () => {
            uni.showToast({
              title: res.data.msg
            })
          }
        })
      }
    })
  } else {
    api.user.destroyRedirect({}).then(res => {
      if (res && res.data.code === 0) {
        uni.redirectTo({
          url: '/pages/common/auth/login/login',
          success: () => {
            uni.showToast({
              title: res.data.msg
            })
          }
        })
      }
    })
  }
}
</script>

<style scoped>

</style>